package com.thoughtworks.bytecode2class.tools;

import com.thoughtworks.bytecode2class.ClassInspector;
import com.thoughtworks.bytecode2class.ClassReader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InvocationsStatistics {
    private static String userage =
            "java com.thoughtworks.bytecode2class.tools.InvocationsStatistics <dir>";

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.err.println(userage);
            return;
        }

        String entrance = args[0];
        ArrayList<String> classFiles = new ArrayList<String>();
        collect(new File(entrance), classFiles);
        StaticsInvocationVisitor visitor = new StaticsInvocationVisitor();
        Map<String, Throwable> errors = new HashMap<String, Throwable>();

        for (String classFile : classFiles) {
            System.out.printf("---> %s\n", classFile);
            ClassReader classReader = new ClassReader();
            try {
                classReader.read(classFile);
                new ClassInspector(classReader, visitor).methods();
            } catch (Throwable e) {
                errors.put(classFile, e);
            }
        }

        System.out.printf("=====Report(%d)=====\n", visitor.map.size());
        System.out.println(visitor.report());
        System.out.printf("=====Erorrs(%d)=====\n", errors.size());
        System.out.println(errors);
    }

    private static void collect(File entrance, List<String> classFiles) {
        if (entrance.isDirectory()) {
            for (File f : entrance.listFiles()) {
                collect(f, classFiles);
            }
        }
        if (entrance.getName().endsWith(".class")) {
            classFiles.add(entrance.getAbsolutePath());
        }
    }
}
